<template>
  <div style="width: 100%; height: 100%" class="main-box">
    <div><img class="logo" src="../../assets/logo1.png"/></div>
    <el-tabs v-model="activeName" class="login-tab">
      <el-tab-pane label="" name="first">
        <div class="login-wrap">
          <div class="login-html">
            <span class="tab">Tbill多人记账</span>
            <input
              id="tab-1"
              type="radio"
              name="tab"
              class="sign-in"
              checked
            /><label for="tab-1" class="tab">登录</label>
            <input id="tab-2" type="radio" name="tab" class="sign-up" /><label
              for="tab-2"
              class="tab"
              >注册</label
            >
            <div class="login-form">
              <div class="sign-in-htm">
                <el-form
                  ref="loginForm"
                  :rules="loginRule"
                  :model="loginForm"
                  class="login-form"
                  auto-complete="on"
                  label-position="left"
                >
                  <el-form-item>
                    <span class="login-form-info">欢迎使用Tbill</span>
                  </el-form-item>
                  <el-form-item class="group" prop="userName">
                    <el-input
                      class="input"
                      v-model="loginForm.userName"
                      placeholder="请输入用户名"
                    />
                  </el-form-item>
                  <el-form-item class="group" prop="password">
                    <el-input
                      type="password"
                      class="input"
                      data-type="password"
                      :show-password="true"
                      v-model="loginForm.password"
                      placeholder="请输入密码"
                    />
                  </el-form-item>
                  <el-form-item class="group">
                    <input id="check" type="checkbox" class="check" checked />
                    <label for="check"
                      ><span class="icon"></span> Keep me Signed in</label
                    >
                  </el-form-item>
                  <el-form-item class="group">
                    <el-button
                      type="primary"
                      class="button"
                      @click="handleLogin()"
                      >登录</el-button
                    >
                  </el-form-item>
                </el-form>
                <div class="hr"></div>
                <div class="foot-lnk">
                  <a href="#forgot">忘记密码?</a>
                </div>
              </div>
              <div class="sign-up-htm">
                <el-form
                  ref="teamForm"
                  :model="teamForm"
                  class="login-form"
                  auto-complete="on"
                  label-position="left"
                >
                  <el-form-item prop="teamName">
                    <div>
                      <h1 class="team-form-title">设置团队信息</h1>
                      <span class="team-form-info"
                        >创建新团队，并填写团队信息，与伙伴们协同记账</span
                      >
                    </div>
                  </el-form-item>
                  <el-form-item prop="teamName">
                    <el-input
                      v-model="teamForm.teamName"
                      placeholder="请输入团队名称"
                    ></el-input>
                  </el-form-item>
                  <el-form-item prop="teamType">
                    <el-select
                      v-model="teamForm.teamType"
                      placeholder="请选择团队类型"
                    >
                      <el-option
                        v-for="item in teamTypeList"
                        :key="item.type"
                        :value="item.type"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item prop="teamMotto">
                    <el-input
                      v-model="teamForm.teamMotto"
                      placeholder="请输入团队座右铭"
                    ></el-input>
                  </el-form-item>
                  <br /><br />
                  <el-form-item prop="teamMotto">
                    <el-button
                      type="primary"
                      style="width: 100%"
                      @click="regisNext('team')"
                      :disabled="nextButtonStatu"
                      >下一步</el-button
                    >
                  </el-form-item>
                </el-form> 

                <div class="hr"></div>
                <div class="foot-lnk">
                  <label
                    ><a @click="regisNext('person')"
                      >不创建团队，注册个人版</a
                    ></label
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="" name="second">
        <div class="login-wrap">
          <div class="login-html">
            <el-page-header @back="lastTip"> </el-page-header>
            <div class="teamBox">
              <div>
                <h1 class="team-form-title">选择团队</h1>
                <span class="team-form-info">您可以进入以下团队</span>
              </div>
              <button
                class="teamButton"
                v-for="item in teamInfo"
                :key="item.teamId"
                :label="item.teamName"
                :value="item.teamName"
                ref="teamButton"
                @click="login(item.id)"
              >
                {{ item.teamName }}
              </button>
            </div>
          </div>
          <!-- <el-button @click="lastTip()"> 上一步 </el-button> -->
        </div></el-tab-pane
      >
      <el-tab-pane label="" name="third">
        <div class="login-wrap">
          <div class="login-html">
            <el-page-header @back="lastTip"> </el-page-header>
            <el-form
              ref="registerForm"
              :rules="registerRule"
              :model="registerForm"
              auto-complete="on"
              label-position="left"
              class="sign-up-form"
              style="margin-top: 20px"
            >
              <el-form-item prop="teamName">
                <div>
                  <h1 class="team-form-title">设置个人信息</h1>
                  <span class="team-form-info"
                    >录入个人信息，即可注册成功，你将默认为团队队长，拥有管理团队的权限</span
                  >
                </div>
              </el-form-item>
              <el-form-item class="group" prop="userName">
                <el-input
                  id="user"
                  type="text"
                  class="input"
                  v-model="registerForm.userName"
                  placeholder="请输入用户名"
                />
              </el-form-item>
              <el-form-item class="group" prop="password">
                <el-input
                  id="pass"
                  type="password"
                  class="input"
                  data-type="password"
                  :show-password="true"
                  v-model="registerForm.password"
                  placeholder="请输入密码"
                />
              </el-form-item>
              <el-form-item class="group" prop="secondPassword">
                <el-input
                  id="pass"
                  type="password"
                  class="input"
                  data-type="password"
                  :show-password="true"
                  v-model="registerForm.secondPassword"
                  placeholder="请再次确认密码"
                />
              </el-form-item>
              <el-form-item class="group" prop="">
                <el-input
                  id="pass"
                  type="text"
                  class="input"
                  v-model="registerForm.telephone"
                  placeholder="请输入手机号"
                />
              </el-form-item>
              <el-form-item class="group">
                <el-button
                  type="primary"
                  class="button"
                  @click="register()"
                  style="width: 100%"
                  >注册</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { getTeamListByUser, addUser, listUser } from "@/api/user";
import { listTeamType } from "@/api/teamType";
import { addTeam, list } from "@/api/team";
import { addUserRole } from "@/api/role";
import { addUserAndTeamRea } from "@/api/teamUser";
export default {
  name: "Login",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入账号"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码不能少于6位"));
      } else {
        callback();
      }
    };
    // const validateCaptchaCode = (rule, value, callback) => {
    //   if (value.length != 4) {
    //     callback(new Error("验证码错误"));
    //   } else {
    //     callback();
    //   }
    // };
    return {
      activeName: "first",
      nextButtonStatu: true,
      teamInfo: [],
      loginForm: {
        userName: "superAdmin",
        password: "123456",
        // captchaCode:""
      },
      registerForm: {
        userName: "",
        password: "",
        secondPassword: "",
        telephone: "",
      },
      loginRule: {
        userName: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
      },
      registerRule: {
        userName: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
        secondPassword: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
        telephone: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
      },
      teamForm: {
        teamName: "",
        teamType: "",
        teamMotto: "",
      },
      passwordType: "password",
      capsTooltip: false,
      loading: true,
      redirect: undefined,
      otherQuery: {},
      captchaImg: "",
      captchaToken: "",
      teamTypeList: [],
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
    teamForm: {
      deep: true,
      handler() {
        this.changeButtonStatus();
      },
    },
  },
  created() {
    // this.getCaptchaImg()
  },
  mounted() {
    if (this.loginForm.userName === "") {
      this.$refs.username.focus();
    } else if (this.loginForm.password === "") {
      this.$refs.password.focus();
    }
    this.listTeamTypes();
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    //  async getCaptchaImg() {
    //   const res = await reqGetCaptcha()
    //   if (res.data.code === IS_OK) {
    //     this.captchaImg = res.data.data.captchaImg
    //     this.captchaToken = res.data.data.token
    //     this.loginForm.captchaCode = ''
    //   }
    // },
    lastTip() {
      this.activeName = "first";
    },
    changeButtonStatus() {
      if (
        this.teamForm.teamName != "" &&
        this.teamForm.teamName != null &&
        this.teamForm.teamType != "" &&
        this.teamForm.teamType != null
      ) {
        this.nextButtonStatu = false;
      } else {
        this.nextButtonStatu = true;
      }
    },
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    async handleLogin() {
      await this.listTeamByUser();
      this.activeName = "second";
    },
    login(teamId) {
      console.log(teamId);
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          const params = {
            userName: this.loginForm.userName,
            password: this.loginForm.password,
            teamId: teamId,
          };
          await this.$store.dispatch("user/login", params);
          console.log("123", this.$store.getters.name);
          this.$message({
            message: "登录成功",
            type: "success",
          });
          this.loading = false;
          this.$router.push({
            path: this.redirect || "/home",
            query: this.otherQuery,
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    async register() {
      var userArr = [];
      //查询所有用户
      await listUser().then((res) => {
        if (res.code == 0) {
          res.data.forEach((user) => {
            userArr.push(user.userName);
          });
        }
      });
      console.log(userArr);
      if (userArr.indexOf(this.registerForm.userName) > -1) {
        this.$message({
          message: "用户名已存在，请更改",
          type: "warning",
        });
      } else {
        await addUser(this.registerForm).then((res) => {
          if (res.code == 0) {
            console.log("添加用户成功");
          }
        });
        if (this.teamForm.teamName != "") {
          await addTeam(this.teamForm).then((res) => {
            if (res.code == 0) {
              console.log("添加团队成功");
            }
          });
          //添加注册的用户为新建团队的队长
          const teamParam = {
            userName: this.registerForm.userName,
            teamName: this.teamForm.teamName,
            relationshipType: 1,
          };
          const roleParam = {
            userName: this.registerForm.userName,
            teamName: this.teamForm.teamName,
            roleName: "团队队长"
          }
          this.addUserAndTeamReation(teamParam,roleParam);
        } else {
          //注册个人版
          const teamParam = {
            userName: this.registerForm.userName,
            teamName: "个人版",
            relationshipType: 0,
          };
          const roleParam = {
            userName: this.registerForm.userName,
            teamName: "个人版",
            roleName: "个人用户"
          }
          this.addUserAndTeamReation(teamParam,roleParam);
        }
      }
    },
    addUserAndTeamReation(teamParam,roleParam) {
      addUserAndTeamRea(teamParam).then((res) => {
        if (res.code == 0) {
          console.log("注册成功");
        }
      });
      addUserRole(roleParam).then((res) => {
        if (res.code == 0) {
         this.$message({
          message: '注册成功！请登录',
          type: 'success'
        });
        this.activeName = "first"
        }
      });
    },

    regisNext(regisType) {
      if (regisType == "person") {
        this.teamForm.teamName = "";
        this.activeName = "third";
      } else {
        //查询所有团队
        var teamArr = [];
        list().then((res) => {
          if (res.code == 0) {
            res.data.forEach((team) => {
              teamArr.push(team.teamName);
            });
          }
          if (teamArr.indexOf(this.teamForm.teamName) > -1) {
            this.$message({
              message: "团队名已存在，请更改",
              type: "warning",
            });
          } else {
            this.activeName = "third";
          }
        });
      }
    },
    // 获取其他参数
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
    listTeamByUser() {
      const params = { userName: this.loginForm.userName };
      getTeamListByUser(params).then((res) => {
        if (res.code == 0) {
          if (res.data.length != 0) {
            this.teamInfo = res.data;
            console.log(res.data);
          } else {
            this.$message({
              message: "你还未注册",
              type: "warn",
            });
          }
        }
      });
      this.loading = false;
    },
    listTeamTypes() {
      listTeamType().then((res) => {
        if (res.code == 0) {
          this.teamTypeList = res.data;
        } else {
          this.$message({
            message: "用户查询失败",
            type: "error",
          });
        }
      });
    },
  },
};
</script>

<style lang="scss">
.main-box {
  background: url(../../assets/images/loginbg.png) no-repeat left;
  background-size: cover;
}
:after,
:before {
  box-sizing: border-box;
}
.clearfix:after,
.clearfix:before {
  content: "";
  display: table;
}
.clearfix:after {
  clear: both;
  display: block;
}
a {
  color: inherit;
  text-decoration: none;
}

.login-wrap {
  width: 100%;
  margin: auto;
  max-width: 525px;
  min-height: 670px;
  position: relative;
  left: 350px;
  background: url(../../assets/images/bg.jpg) no-repeat left;
  box-shadow: 0 12px 15px 0 rgba(0, 0, 0, 0.24),
    0 17px 50px 0 rgba(0, 0, 0, 0.19);
}
.login-html {
  width: 100%;
  height: 100%;
  position: absolute;
  padding: 90px 70px 50px 70px;
  background: #93a599;
}
.login-html .sign-in-htm,
.login-html .sign-up-htm {
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  position: absolute;
  transform: rotateY(180deg);
  backface-visibility: hidden;
  transition: all 0.4s linear;
}
.login-html .sign-in,
.login-html .sign-up,
.login-form .group .check {
  display: none;
}
.login-html .tab,
.login-form .group .label,
.login-form .group .button {
  text-transform: uppercase;
}
.login-html .tab {
  font-size: 22px;
  color: rgb(14, 13, 13);
  margin-right: 15px;
  padding-bottom: 5px;
  margin: 0 15px 10px 0;
  display: inline-block;
  border-bottom: 2px solid transparent;
}
.login-html .sign-in:checked + .tab,
.login-html .sign-up:checked + .tab {
  color: rgb(219, 219, 219);
  border-color: #f7f7f8;
}
.login-form {
  min-height: 345px;
  position: relative;
  perspective: 1000px;
  transform-style: preserve-3d;
}
.login-form .group {
  margin-bottom: 28px;
}
.login-form .group .label,
.login-form .group .el-input,
.login-form .group .button {
  width: 100%;
  color: #fff;
  display: block;
}
.login-form .group .el-input,
.login-form .group .button {
  border: none;
  padding: 15px, 20px;
}
.login-form .group input[data-type="password"] {
  text-security: circle;
  -webkit-text-security: circle;
}
.el-select {
  width: 100%;
}
// .login-form .group input {
//   background: rgba(223, 234, 222, 0.1);
//   border: 0px;
//   border-radius: 25px;
//   color: white;
// }
.el-button {
  padding: 15px 20px;
}
.sign-up-form .el-form-item__content {
  line-height: 20px;
}
.login-form .group .label {
  color: rgb(74, 73, 73);
  font-size: 12px;
}
.login-form .group label .icon {
  width: 15px;
  height: 15px;
  border-radius: 2px;
  position: relative;
  display: inline-block;
  background: rgba(255, 255, 255, 0.1);
}
.login-form .group label .icon:before,
.login-form .group label .icon:after {
  content: "";
  width: 10px;
  height: 2px;
  background: #fff;
  position: absolute;
  transition: all 0.2s ease-in-out 0s;
}
.login-form .group label .icon:before {
  left: 3px;
  width: 5px;
  bottom: 6px;
  transform: scale(0) rotate(0);
}
.login-form .group label .icon:after {
  top: 6px;
  right: 0;
  transform: scale(0) rotate(0);
}
.login-form .group .check:checked + label {
  color: #fff;
}
.login-form .group .check:checked + label .icon {
  background: #1161ee;
}
.login-form .group .check:checked + label .icon:before {
  transform: scale(1) rotate(45deg);
}
.login-form .group .check:checked + label .icon:after {
  transform: scale(1) rotate(-45deg);
}
.login-html
  .sign-in:checked
  + .tab
  + .sign-up
  + .tab
  + .login-form
  .sign-in-htm {
  transform: rotate(0);
}
.login-html .sign-up:checked + .tab + .login-form .sign-up-htm {
  transform: rotate(0);
}
.hr {
  height: 2px;
  margin: 60px 0 50px 0;
  background: rgba(255, 255, 255, 0.2);
}
.foot-lnk {
  text-align: center;
}
.login-tab .el-tabs__nav-scroll {
  height: 0px !important;
}
.teamButton {
  background: #586e61;
  width: 100%;
  height: 80px;
  margin-top: 10px;
  color: white;
  font-weight: 300;
  font-family: Verdana, Geneva, Tahoma, sans-serif;
  font-size: 20px;
  border-radius: 10px;
}
.teamButton:hover {
  background: #9fb7a8;
  font-size: 24px;
}
.teamBox {
  position: relative;
  top: 20px;
}
.el-page-header__left {
  color: rgb(14, 13, 13);
}
.team-form-title {
  font-size: 20px;
  color: #252424;
}
.team-form-info {
  font-size: 14px;
  color: #525352;
}
.login-form-info {
  font-size: 16px;
  color: #525352;
}
.logo{
  position: relative;
  float: left;
  width: 150px;
  left: 10px;
  top:10px;
}
</style>
